//
//  GoodSelectVC.m
//  danpin
//
//  Created by chuangjia on 6/7/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "GoodSelectVC.h"
#import "BaseModel.h"
#import "MDSearchBarController.h"
#import "CellConfig.h"
#import "GoodCreateVC.h"

@interface GoodSelectVC ()<UITableViewDataSource,UITableViewDelegate,MDSearchBarViewControllerDelegate,UITextFieldDelegate,OHAttributedLabelDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,strong)NSMutableArray *setcionArray;
@property(nonatomic,strong)void(^actionBlock)(id,id);
//
@property (nonatomic, strong) MDSearchBar * searchBar;
@property (nonatomic, strong) MDSearchBarController * searchBarController;
@property(nonatomic,strong) NSMutableArray *searchArray;
@property (nonatomic,strong) NSString *searchWord;

@property (nonatomic,assign) BOOL isSearchStatue;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)int currentPage;

@end

@implementation GoodSelectVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor =[UIColor whiteColor];
    self.isComment =YES;
    self.navTitle =@"选择单品";
    if (!_setcionArray) {
        _setcionArray =[[NSMutableArray alloc] init];
    }
    if (!_searchArray) {
        _searchArray =[[NSMutableArray alloc] init];
    }
    _searchWord=@"";
    _isLoadFinished =NO;
    _isSearchStatue=NO;
    _currentPage=0;
    [self initUI];
    [self initSearchView];
 //   [ZShare showAnimationView:self.view center:CGPointZero];
    [self gataCategoryDataWithWord:@"" isSearch:NO];
}
-(void)clickNavEvent:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 0:
        {
            self.actionBlock =nil;
            [self.searchBar removeFromSuperview];
            self.searchBar=nil;
            self.searchBarController.delegate= nil;
            self.searchBarController.active =NO;
            self.searchBarController=nil;
            self.tbView.tableHeaderView=nil;
            self.tbView.tableFooterView =nil;
            if (self.navigationController) {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
      
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
      DLog(@"%s", __PRETTY_FUNCTION__);
     [_setcionArray removeAllObjects];
     [_searchArray removeAllObjects];
}
-(void)dealloc
{
    [self.setcionArray removeAllObjects];
    self.setcionArray =nil;
    [self.searchArray removeAllObjects];
    self.searchArray =nil;
    self.actionBlock =nil;
    self.searchBar=nil;
    self.searchBarController.delegate= nil;
    self.searchBarController.active =NO;
    self.searchBarController=nil;
   
    
    self.tbView.dataSource=nil;
    self.tbView.delegate=nil;
    self.tbView.tableHeaderView=nil;
    self.tbView.tableFooterView =nil;
    self.tbView =nil;
    DLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)setSelectedCallBack:(void(^)(id,id))callback
{
    self.actionBlock=callback;
}

//
-(void)initUI
{
    if (_tbView) {
        [_tbView removeFromSuperview];
        _tbView=nil;
    }
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navHeight, self.view.bounds.size.width, self.view.bounds.size.height-self.navHeight) style:UITableViewStylePlain];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =[UIColor whiteColor];
    _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbView.showsVerticalScrollIndicator = NO;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
    __weak typeof (self) wSelf = self;
    [_tbView addInfiniteScrollingWithActionHandler:^{
        
        if (wSelf.isLoadFinished) {
            //停止菊花
            [wSelf.tbView.infiniteScrollingView stopAnimating];
            [wSelf.tbView setShowsInfiniteScrolling:NO];
            return;
        }
        [wSelf.tbView.infiniteScrollingView startAnimating];
        if (wSelf.isSearchStatue) {
            wSelf.currentPage =(int)wSelf.searchArray.count+1;
        }else
        {
            wSelf.currentPage=(int)[wSelf.setcionArray count]+1;
        }
        [wSelf gataCategoryDataWithWord:wSelf.searchWord isSearch:wSelf.isSearchStatue];
    }];
    
}
#pragma mark - tableview
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView==_tbView) {
        return self.setcionArray.count;
    }else
    {
        if (self.searchArray.count==0) {
            return 1;
        }
        return self.searchArray.count;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_tbView) {
        NSDictionary *dict =[self.setcionArray objectAtIndex:indexPath.row];
        return [ShaiDanNameCell returnCellHeight:dict];
    }else
    {
        if (self.searchArray.count==0) {
            return tableView.frame.size.height;
        }
        NSDictionary *dict =[self.searchArray objectAtIndex:indexPath.row];
        return [ShaiDanNameCell returnCellHeight:dict];
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
    if (tableView==_tbView) {
        ShaiDanNameCell *cell = (ShaiDanNameCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
        if(cell == nil)
        {
            cell = [[ShaiDanNameCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.contentView.backgroundColor = [UIColor clearColor];
            cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
            cell.selectedBackgroundView.backgroundColor =UIColorFromRGB(0xf4f4f4);
            cell.imageView.frame =CGRectMake(10, 10, 80, 80);
        }
        
        if (indexPath.row >=self.setcionArray.count) {
            return cell;
        }
        NSDictionary *dict =[self.setcionArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:@"ShaiDanNameCell" indexPath:indexPath];
        return cell;
    }else
    {
        if (self.searchArray.count==0) {
           cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@"defaultView"];
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"defaultView"];
                cell.backgroundColor=[UIColor clearColor];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            UIView* currentView = [cell viewWithTag:100000];
            [currentView removeFromSuperview];
            currentView=nil;
            [cell addSubview:[self defaultView]];
           
            return cell;
        }
        ShaiDanNameCell *cell = (ShaiDanNameCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
        if(cell == nil)
        {
            cell = [[ShaiDanNameCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.contentView.backgroundColor = [UIColor clearColor];
            cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
            cell.selectedBackgroundView.backgroundColor =UIColorFromRGB(0xf4f4f4);
            cell.imageView.frame =CGRectMake(10, 10, 80, 80);
        }
        
        if (indexPath.row >=self.searchArray.count) {
            return cell;
        }
        NSDictionary *dict =[self.searchArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:@"ShaiDanNameCell" indexPath:indexPath];
        return cell;
    
    }
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == _tbView)
    {
        if (indexPath.row>=self.setcionArray.count) {
            return;
        }
        NSDictionary *dict =[self.setcionArray objectAtIndex:indexPath.row];
        if (self.actionBlock) {
            self.actionBlock(dict,@"brand");
        }
        [self.searchBar removeFromSuperview];
        self.searchBar=nil;
        self.searchBarController.delegate= nil;
        self.searchBarController.active =NO;
        self.searchBarController=nil;
        self.tbView.tableHeaderView=nil;
        self.tbView.tableFooterView =nil;
        [self.navigationController popViewControllerAnimated:YES];
    }else
    {
        if (indexPath.row>=self.searchArray.count) {
            return;
        }
        NSDictionary *dict =[self.searchArray objectAtIndex:indexPath.row];
        if (self.actionBlock) {
            self.actionBlock(dict,@"brand");
        }
        [self.searchBar removeFromSuperview];
        self.searchBar=nil;
        self.searchBarController.delegate= nil;
        self.searchBarController.active =NO;
        self.searchBarController=nil;
        self.tbView.tableHeaderView=nil;
        self.tbView.tableFooterView =nil;
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

//////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////
-(void)initSearchView
{
    //
    if (_searchBar) {
        [_searchBar removeFromSuperview];
        _searchBar=nil;
    }
    self.searchBar =[[MDSearchBar alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 28)];
    self.tbView.tableHeaderView=self.searchBar;
    
    if (_searchBarController) {
        _searchBarController.searchView.searchTable=nil;
        _searchBarController.delegate=nil;
        _searchBarController.searchBarView=nil;
        _searchBarController=nil;
    }
    self.searchBarController = [[MDSearchBarController alloc] init];
    self.searchBarController.delegate= self;
    self.searchBarController.searchBarView.frame = self.searchBar.frame;
    [self.searchBar.superview addSubview:self.searchBarController.searchBarView];
    [self.searchBar removeFromSuperview];
    self.searchBar = self.searchBarController.searchBarView;
    self.searchBar.textField.placeholder = @"搜索单品...";
    self.searchBarController.searchView.searchTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    __weak typeof (self) wSelf = self;
    [self.searchBarController.searchView.searchTable addInfiniteScrollingWithActionHandler:^{
        
        if (wSelf.isLoadFinished) {
            //停止菊花
            [wSelf.searchBarController.searchView.searchTable.infiniteScrollingView stopAnimating];
            [wSelf.searchBarController.searchView.searchTable setShowsInfiniteScrolling:NO];
            return;
        }
        [wSelf.searchBarController.searchView.searchTable.infiniteScrollingView startAnimating];
        wSelf.currentPage =(int)wSelf.searchArray.count+1;
        [wSelf gataCategoryDataWithWord:wSelf.searchWord isSearch:YES];
    }];
    
}
-(void)searchBar:(MDSearchBarController *)searchBarController searchWithText:(NSString *)text{
    self.currentPage=0;
    [self gataCategoryDataWithWord:text isSearch:YES];
}
-(void)searchBar:(MDSearchBarController *)searchBarController searchWithActive:(BOOL)active
{
    self.currentPage=0;
    [self.searchArray removeAllObjects];
    [self.searchBarController reloadData];
}
-(void)searchBar:(MDSearchBarController *)searchBarController searchWithKeyWord:(NSString *)isSearch
{
     self.currentPage=0;
    [self gataCategoryDataWithWord:isSearch isSearch:YES];
}
//
-(void)gataCategoryDataWithWord:(NSString*)word isSearch:(BOOL)isSearch
{
    _searchWord=word;
    if (isSearch) {
        _searchWord=word;
        self.searchBarController.searchView.searchTable.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-self.navHeight-28);
    }
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:word forKey:@"word"];
    [dict setValue:@"ware" forKey:@"action"];
    [dict setValue:self.cate_id forKey:@"cate_id"];
    [dict setValue:self.brand_id forKey:@"brand_id"];
    [dict setValue:[NSString stringWithFormat:@"%d",self.currentPage] forKey:@"from"];
    __weak typeof (self) wSelf = self;
    [BaseModel suggestion:dict success:^(AFHTTPRequestOperation *operation, id result) {
        [wSelf parserResultObject:result isSearch:isSearch];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
        [wSelf.searchBarController.searchView.searchTable.infiniteScrollingView stopAnimating];
 //       [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
        [wSelf.tbView.infiniteScrollingView stopAnimating];
        [wSelf.searchBarController.searchView.searchTable.infiniteScrollingView stopAnimating];
//        [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
}
-(void)parserResultObject:(id)resultObject isSearch:(BOOL)isSearch
{
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        id data =[resultObject objectForKey:@"data"];
        if (data && [data isKindOfClass:[NSArray class]]) {
            if (isSearch) {
                if (self.currentPage==0) {
                    [self.searchArray removeAllObjects];
                }
                for (id dict in data) {
                    [self.searchArray addObject:dict];
                }
            }else{
                if (self.currentPage==0) {
                    [self.setcionArray removeAllObjects];
                }
                for (id dict in data) {
                    [self.setcionArray addObject:dict];
                }
            }
            
        }
        
    }
    //end
    self.isLoadFinished =  [[resultObject objectForKey:@"end"] boolValue];
    if (self.isLoadFinished) {
        [self.tbView.infiniteScrollingView stopAnimating];
        [self.tbView setShowsInfiniteScrolling:NO];
        
        [self.searchBarController.searchView.searchTable.infiniteScrollingView stopAnimating];
        [self.searchBarController.searchView.searchTable setShowsInfiniteScrolling:NO];
        NSString *end_msg =[resultObject objectForKey:@"end_msg"];
        self.tbView.tableFooterView =[ZShare footerView:end_msg];
        self.searchBarController.searchView.searchTable.tableFooterView=[ZShare footerView:end_msg];
    }
    if(isSearch)
    {
        [self.searchBarController reloadData];
        
    }else{
        [_tbView reloadData];
    }
    
    
}

//无数据展示样式
-(UIView *)defaultView
{
   
    UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0,0,self.view.bounds.size.width, self.view.bounds.size.height-100)];
    view.backgroundColor=[UIColor clearColor];
    view.tag =100000;
    UIImageView *wifiImageView =[[UIImageView alloc] initWithFrame:CGRectMake((view.frame.size.width-140)/2,PHOTO_FRAME_WIDTH*4,140, 140)];
    wifiImageView.image =[UIImage imageNamed:@"no_list_image.png"];
    wifiImageView.tag =5048;
    [view addSubview:wifiImageView];
   
    UILabel* Infolabel = [[UILabel alloc]initWithFrame:CGRectMake(0, wifiImageView.frame.origin.y+140, view.frame.size.width, 20)];
    Infolabel.backgroundColor = [UIColor clearColor];
    Infolabel.textAlignment = NSTextAlignmentCenter;
    Infolabel.textColor = UIColorFromRGB(0xcccccc);
    Infolabel.font = FONT(14);
    Infolabel.text =@"暂无单品";
    [view addSubview:Infolabel];
   
    UIView *line =[[UIView alloc] initWithFrame:CGRectMake(PHOTO_FRAME_WIDTH*2,wifiImageView.frame.origin.y+170,self.view.bounds.size.width-PHOTO_FRAME_WIDTH*4, 0.5)];
    line.backgroundColor= UIColorFromRGB(0xcccccc);
    [view addSubview:line];
    line=nil;
    UILabel* Infos = [[UILabel alloc]initWithFrame:CGRectMake(0, wifiImageView.frame.origin.y+180, view.frame.size.width, 20)];
    Infos.backgroundColor = [UIColor clearColor];
    Infos.textAlignment = NSTextAlignmentCenter;
    Infos.textColor = UIColorFromRGB(0xcccccc);
    Infos.font = FONT(14);
    Infos.text =@"你可以新建单品来完成晒单";
    [view addSubview:Infos];
   
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame =CGRectMake((view.frame.size.width-PHOTO_FRAME_WIDTH*8)/2, wifiImageView.frame.origin.y+210, PHOTO_FRAME_WIDTH*8, 30);
    button.backgroundColor =UIColorFromRGB(0x285790);
    button.layer.cornerRadius =3;
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font =FONT(14);
    [button setTitle:@"新建单品" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(createDanpinAction) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    return view;
}
-(void)createDanpinAction
{
    self.searchBarController.active =NO;
    GoodCreateVC *goodc =[[GoodCreateVC alloc] init];
    [self.navigationController pushViewController:goodc animated:YES];
    goodc = nil;
}
@end
